<template>
  <a-cascader
    v-model="cityCode"
    allowClear
    :default-value="defaultValue"
    :options="options"
    placeholder="请选择"
    allow-search
    :trigger-props="{ updateAtScroll: true }"
    @change="changeFn"
  />
</template>
<script setup>
  import { ref } from 'vue'
  import { useVModel } from '@vueuse/core'
  import { getProvinceCityList } from '@/api/common'
  const props = defineProps({
    modelValue: String,
    defaultValue: Array,
  })
  const emit = defineEmits(['update:modelValue', 'change'])
  const cityCode = useVModel(props, 'modelValue', emit)

  const options = ref([])

  // 处理 prop
  const handleData = (result) => {
    return result.map((item) => {
      let childrenList = item.list
      let children = []
      if (childrenList && childrenList.length > 0) {
        children = childrenList.map((childItem) => {
          return {
            value: childItem.code,
            label: childItem.name,
          }
        })
      }
      return {
        value: item.code,
        label: item.name,
        children,
      }
    })
  }

  const loadData = () => {
    getProvinceCityList().then(({ result }) => {
      options.value = handleData(result)
    })
  }

  // 向外导出 change 事件
  const changeFn = (value) => {
    let opts = options.value
    let provinceOption = {}
    let cityOption = {}
    for (let i = 0; i < opts.length; i++) {
      let province = opts[i]
      if (province.children) {
        let targetCity = province.children.find((city) => city.value == value)
        if (targetCity) {
          cityOption = targetCity
          provinceOption = province
          break
        }
      }
    }
    emit('change', value, {
      provinceCode: provinceOption.value,
      provinceName: provinceOption.label,
      cityCode: cityOption.value,
      cityName: cityOption.label,
    })
  }

  loadData()
</script>
<style lang="less" scoped></style>
